<template>
  <div id="map_demo2">

    <baidu-map class="map" :center="locations" :zoom="zoom" @ready="handler">

    </baidu-map>

  </div>
</template>

<script>
export default {
  data() {
    return {
      zoom: 20,
      center: { lng: 0, lat: 0 },
      BMap: null,
      map: null,
      locations: {}
    }
  },
  methods: {
    handler({ BMap, map }) {
      // 保存百度地图类
      this.BMap = BMap
      this.map = map
      this.center = ''
      this.zoom = 15
      const geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition((r) => {
        console.log('res', r)
        // IP地址赋值给locations对象
        this.locations.lng = r.point.lng
        this.locations.lat = r.point.lat



        // 获取当前位置的经纬度
        var mk = new BMap.Marker(r.point);
        map.addOverlay(mk); //标出当前位置
        map.panTo(r.point); // 将地图中心设置为当前位置

        // 对当前位置进行逆地理编码
        var pt = r.point;
        var geoc = new BMap.Geocoder();
        geoc.getLocation(pt, function(rs){
          var addComp = rs.addressComponents;
          console.log('addComp', addComp)
          // 获取到的详细地址信息
          var address = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber;
          alert("当前位置的详细地址是：\n" + address);
        });






      }, {enableHighAccuracy: true})
    }
  }
}
</script>

<style>
.map {
  width: 100%;
  height: 100vh;
}
</style>
